﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Path
{
    public class CreatePathHandler : IRequestHandler<CreatePathCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PathModel> _pathRepository;
        private readonly IMapper _mapper;

        public CreatePathHandler(IBaseRepository<PathModel> pathRepository, IMapper mapper)
        {
            _pathRepository = pathRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(CreatePathCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int>result = new ApiResult<int>();

            var path = _pathRepository.GetAll().FirstOrDefault(p => p.MenuName == request.MenuName && p.PartentId==request.PartentId && p.IsDelete == false);
            if (path != null)
            {
                result.Code=StatusEnum.Fail;
                result.Message = "菜单名称已存在";
                return Task.FromResult(result);
            }
            var model = _mapper.Map<PathModel>(request);
            model.CreateTime=DateTime.Now;
            model.Creater = "张三";
            model.UpdateTime=null;

            //排序字段
            int Orderby =_pathRepository.GetAll().Select(m => m.Orderby).ToList().DefaultIfEmpty(0).Max(); 
            model.Orderby = Orderby+1;

            var res =_pathRepository.Add(model);
            if (res > 0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "添加成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "添加失败";
            }
            return Task.FromResult(result);
        }
    }
}
